# Reksio - Memory Map Editor
# Copyright (C) 2023 CERN
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# In applying this licence, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization or
# submit itself to any jurisdiction.

import reksio


class BitsRange:
    def __init__(self, start, stop):
        self.start = int(start)
        self.stop = int(stop)
        self.bits = set(range(self.start, self.stop + 1))


def validate(attr):
    attr_node = attr.parentNode
    reg_name = attr_node.name

    reg_width = attr.value
    if reg_width == '':
        return True

    reg_width = int(reg_width)
    allbits = set(range(reg_width))

    reg_fields = [child for child in attr_node.children() if child.type == 'field']

    already_used_bits = set()

    for field in reg_fields:
        try:
            # reksio format field range: '{stop bit}-{start bit}', e.g. '3-1'
            field_ranges = field.range.value.rsplit('-', 1)
            field_bits = BitsRange(field_ranges[-1], field_ranges[0])
        except (AttributeError, ValueError):
            continue

        is_bits_range_correct = (field_bits.stop < field_bits.start)
        is_bits_overlap = (field_bits.bits & already_used_bits)
        is_bits_out_of_range = not (field_bits.bits <= allbits)

        if is_bits_overlap or is_bits_out_of_range or is_bits_range_correct:
            err_msg = [f'In register: "{reg_name}" -> in field: "{field.name}"']

            if is_bits_overlap:
                err_msg.append('overlapped bits detected!')

            if is_bits_out_of_range:
                err_msg.append('bits out of register range detected!')

            if is_bits_range_correct:
                err_msg.append(f'incorrect range configuration! (stop bit: "{field_bits.stop}" >'
                               f'start bit:"{field_bits.start}")')

            reksio.warn(' - '.join(err_msg))
            return False

        already_used_bits = already_used_bits | field_bits.bits

    return True


def getMessage():
    return 'Problem with register fields range!'
